import Shop from '../../model/shop'
import DlyAdminUser from '../../model/dlyadminuser'
import ApiError from '../../error/ApiError'
import ApiErrorNames from '../../error/ApiErrorNames'
import AiUser from '../../model/AiUser'

class ShopController {
	static async list(ctx) {
		// console.log('ctx', ctx.request.header.jwtuserinfo)
		const jwtuserinfo = ctx.request.header.jwtuserinfo

		const {
			page = 1,
			pageSize = 20,
			isBuy = '',
			shop_id = '',
			shop_name = '',
			shop_phone = '',
			user_phone = '',
			isProxy = '',
			proxyPhone = '',
		} = ctx.query
		// 获取全部数据
		const findData = {
			isBuy,
			shop_id,
			shop_name: shop_name ? new RegExp(shop_name) : '',
			shop_phone,
			user_phone,
			proxyId: '',
		}
		if (
			jwtuserinfo.roleName === 'adminSp' ||
			jwtuserinfo.roleName === 'admin'
		) {
			findData.proxyId = ''
		}
		if (jwtuserinfo.roleName === 'proxy1') {
			const pritids = await DlyAdminUser.find({
				parentId: jwtuserinfo._id,
			})
			if (pritids.length > 0) {
				const litsadrtid = [
					jwtuserinfo._id,
					...pritids.map((item) => item._id),
				]
				findData.proxyId = { $in: litsadrtid }
			} else {
				findData.proxyId = jwtuserinfo._id
			}
		}
		if (jwtuserinfo.roleName === 'proxy2') {
			findData.proxyId = jwtuserinfo._id
		}
		Object.keys(findData).forEach((key) => {
			if (findData[key] === '') {
				delete findData[key]
			}
		})
		// if (isProxy != '') {
		// 	if (isProxy == '1') {
		// 		findData.proxyId = { $ne: null }
		// 	}
		// 	if (isProxy == '0') {
		// 		findData.proxyId = null
		// 	}
		// }
		if (proxyPhone != '') {
			const getProxyData = await DlyAdminUser.findOne({
				phone: proxyPhone,
			})
			if (!getProxyData) {
				ctx.body = { list: [], total: 0 }
				return
			}
			findData.proxyId = getProxyData._id
		}

		const result = await Shop.find(findData)
			.populate('proxyId')
			.populate('proxyLinkId')
			.limit(pageSize * 1)
			.skip((page - 1) * pageSize)
			.sort({ createTime: -1 })
		// console.log('result', result)
		const total = await Shop.countDocuments(findData)
		ctx.body = { list: result, total }
	}
	static async dlyuserlist(ctx) {
		const jwtuserinfo = ctx.request.header.jwtuserinfo
		if (
			jwtuserinfo.roleName !== 'adminSp' &&
			jwtuserinfo.roleName !== 'admin'
		) {
			throw new ApiError(ApiErrorNames.NO_PERMISSION)
		}
		const { page = 1, pageSize = 20, phone = '' } = ctx.query
		const param = {
			phone,
		}
		for (let key in param) {
			if (!param[key]) delete param[key]
		}
		const list = await AiUser.find(param)
			.limit(pageSize * 1)
			.skip((page - 1) * pageSize)
			.sort({ createTime: -1 })
		// const result = await DlyAdminUser.find({ parentId: jwtuserinfo._id })
		const total = await AiUser.countDocuments(param)
		ctx.body = {
			list,
			total,
		}
	}
}

export default ShopController
